package yagwl.service.demo;

import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;

import javax.persistence.EntityManager;
import javax.persistence.Query;

import yagwl.service.util.db.DaoContext;
import yagwl.service.util.svc.BaseException;
import yagwl.service.util.svc.BaseException.ErrorCode;

public class ProductDao {

  private static final Logger log = Logger
      .getLogger(ProductDao.class.getName());

  private DaoContext ctx;

  public ProductDao(DaoContext ctx) {
    this.ctx = ctx;
  }

  public ProductEntity getProduct(Long productId) {
     ProductEntity prd = ctx.em().find(ProductEntity.class, productId);
    return prd;
  }

  @SuppressWarnings("unchecked")
  public List<ProductEntity> getProducts() {
    EntityManager em = ctx.em();
    Query q = em.createQuery("select from ProductEntity");
    List<ProductEntity> list = null;
    try {
      list = (List<ProductEntity>) q.getResultList();
      for (@SuppressWarnings("unused") ProductEntity prd : list)
        ;
    } catch (Exception e) {
      log.severe(e.toString());
      list = new ArrayList<ProductEntity>();
    }
    print(list);
    return list;
  }

  public ProductEntity createProduct(ProductEntity prd) {
    if (prd.getPrice() < 0)
      throw new BaseException(ErrorCode.INVALID_NUMBER);
    EntityManager em = ctx.em();
    try {
      em.getTransaction().begin();
      em.persist(prd);
      em.getTransaction().commit();
    } catch (Exception e) {
      log.severe(e.toString());
      em.getTransaction().rollback();
      throw new BaseException(ErrorCode.INTERNAL_TRANSACTION_ERROR, e);
    }
    return prd;
  }

  public void updateProduct(ProductEntity prd) {
    EntityManager em = ctx.em();
    try {
      em.getTransaction().begin();
      em.persist(prd);
      em.getTransaction().commit();
    } catch (Exception e) {
      log.severe(e.toString());
      em.getTransaction().rollback();
      throw new BaseException(ErrorCode.INTERNAL_TRANSACTION_ERROR, e);
    }
  }

  public void deleteProduct(Long id) {
    EntityManager em = ctx.em();
    em.getTransaction().begin();
    Query delq = em.createQuery(
        "delete from ProductEntity where productId = :id").setParameter("id",
        id);
    log.info("Deleting: " + id);
    delq.executeUpdate();
    em.getTransaction().commit();
  }

  private void print(List<ProductEntity> list) {
    for (ProductEntity prd : list) {
      log.finer(prd.print());
    }
  }

}
